# Builds the PyMite VM as an archive
#
# This Makefile is not meant to be invoked directly.
# This Makefile is meant to be invoked by a Makefile in src/platform/<plat>/
# and requires the following environment variables to be exported by the caller:
#   CC OBJCOPY NM CFLAGS AR IPM PM_LIB_FN PLATFORM
#
# The primary function of this makefile is to:
#
#   1. Build pmstdlib_img.c and pmstdlib_nat.c from PMSTDLIB_SOURCES
#   2. Build libpmvm_<plat>.a from all *.c files
#


PLATFORM ?= desktop
PMIMGCREATOR := ../tools/pmImgCreator.py
PMSTDLIB_SOURCES = ../lib/list.py \
                   ../lib/dict.py \
                   ../lib/__bi.py \
                   ../lib/sys.py \
                   ../lib/string.py
ifeq ($(IPM),true)
	PMSTDLIB_SOURCES += ../lib/ipm.py
endif


SOURCE_IMG := pmstdlib_img.c
SOURCE_NAT := pmstdlib_nat.c

ARFLAGS = rcs
SOURCES = $(wildcard *.c) $(SOURCE_IMG) $(SOURCE_NAT)
OBJECTS = $(SOURCES:.c=.o)
INDENT := $(call pathsearch,indent)


# Fix flags from WinARM/WinAVR Makefile
# If ALL_CFLAGS is defined, overwrite CFLAGS
ifneq ($(ALL_CFLAGS),)
    CFLAGS = $(ALL_CFLAGS)
	IPM=true
endif
# If RM does not exist, define it as REMOVE
ifeq ($(RM),)
    RM = $(REMOVE)
endif


.PHONY: all size indent clean
# Must delete/rebuild these intermediate files because they depend on the platform
#.INTERMEDIATE: $(SOURCE_IMG) $(SOURCE_NAT)

# Default action is to build the archive from object files
all : $(SOURCE_IMG) $(SOURCE_NAT) $(PM_LIB_FN)

# Translate Python code to bytecoded C images
bytecode : $(SOURCE_IMG) $(SOURCE_NAT) ../platform/$(PLATFORM)/pmfeatures.h

# The archive is generated by placing object files inside it
$(PM_LIB_FN) : $(PM_LIB_FN)($(OBJECTS))

# Build the standard library into an image file and native function file
$(SOURCE_IMG) $(SOURCE_NAT) : $(PMSTDLIB_SOURCES) $(PMIMGCREATOR) ../platform/$(PLATFORM)/pmfeatures.py
	$(PMIMGCREATOR) -f ../platform/$(PLATFORM)/pmfeatures.py -c -s --memspace=flash -o $(SOURCE_IMG) --native-file=$(SOURCE_NAT) $(PMSTDLIB_SOURCES)

size : $(PM_LIB_FN)
	@$(SIZE) $(PM_LIB_FN)

# Runs GNU indent on the source files
indent :
	$(if $(INDENT), $(INDENT) *.c *.h)

# Remove files made by default make
clean :
	@$(RM) $(PM_LIB_FN) $(SOURCE_IMG) $(SOURCE_NAT)
#	@$(RM) $(OBJECTS)
